package com.sky.aspect;


import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * AutoFill 切入面类
 * @Author: WangHongKun
 * @Date: 2022/9/22 16:58
 * @Email: 2028911483@qq.com
 * @Phone: 18683977706
 */
@Slf4j
@Aspect
@Component  //注册进入spring容器
public class AutoFillAspect {
    //切入点
    @Pointcut("execution(* com.sky.mapper.*.*(..))   && @annotation(com.sky.annotation.AutoFill)")
    public void   MethodPointCut(){}

    @Before("MethodPointCut()")
    public void  beforeMethod(JoinPoint joinPoint) throws Exception{
        log.info("开始进行公共字段自动填充...");
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        //获得注解对象
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        //获得value
        OperationType operationType = autoFill.value();

        //获取对象
        Object[] args = joinPoint.getArgs();

        //获取时间，以及id
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        //当获取的mapper对象为空时 直接返回
        if(args.length ==0 ||   args==null){
            return;
        }
        //取出mapper对象
        Object arg = args[0];
        //INSERT 包含 updateNumber 和 create
        if (operationType  == OperationType.INSERT){
            Method method1 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method method2 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method method3 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            Method method4 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

            method1.invoke(arg,now);
            method2.invoke(arg,now);
            method3.invoke(arg,currentId);
            method4.invoke(arg,currentId);
        }
        //UPDATE 只包含 updateNumber
        else if (operationType  == OperationType.UPDATE){
            Method method2 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method method4 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

            method2.invoke(arg,now);
            method4.invoke(arg,currentId);
        }
        return;



    }



}
